package com.tms.control;

import com.github.pagehelper.PageInfo;
import com.tms.domain.*;
import com.tms.service.*;
import com.tms.utils.Data;
import com.tms.utils.JsonResult;
import com.tms.utils.description.DescriptionService;
import com.tms.utils.token.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import static com.tms.core.constants.BillConstants.ERROR_PARSE_DATE;
import static com.tms.core.constants.StatusConstants.*;
import static com.tms.core.constants.UseRecordConstants.*;

/**
 * 进出库记录
 */
@RestController
@RequestMapping("/api/useRecords")
public class UseRecordController extends BaseController {

    @Autowired
    private UseRecordService useRecordService;

    @Autowired
    private UserService userService;

    @Autowired
    private ProductLineService productLineService;

    @Autowired
    private ToolService toolService;

    @Autowired
    private LocationService locationService;

    @Autowired
    private LifeCycleService lifeCycleService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private LifeCycleStatusService lifeCycleStatusService;

    @Autowired
    private ToolStatusService toolStatusService;

    @Autowired
    private UseRecordStatusService useRecordStatusService;

    @Autowired
    private DescriptionService descriptionService;

    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private com.tms.utils.DateUtil dateUtil = new com.tms.utils.DateUtil();


     /**
     * 新增进出库记录
     * @param map 获取信息
     * @param req 获取token
     * @return 成功返回success以及记录内容，失败返回failed并说明理由
     */
    @PostMapping
    public JsonResult addUseRecord(@RequestBody Map<String, String> map, HttpServletRequest req) {
       
        //从map里取出需要的所有的参数
        int staffId = Integer.parseInt(map.get("staffId"));
        int productLineId = Integer.parseInt(map.get("productLineId"));
        int toolId = Integer.parseInt(map.get("toolId"));
        //确定提交时间
        Date time;
        try {
            time = dateUtil.getCurrentDate();
        } catch (ParseException e) {
            e.printStackTrace();
            return new JsonResult(ERROR_PARSE_DATE.getStatus(), ERROR_PARSE_DATE.getDesc());
        }
        int status = Integer.parseInt(map.get("status"));
        int locationId = Integer.parseInt(map.get("locationId"));

        //从数据库取出数据并校验数据是否可用
        Tool tool = toolService.findToolById(toolId);
        Staff staff = userService.findStaffById(staffId);
        Location location = locationService.findLocationById(locationId);
        ProductLine productLine = productLineService.findProductLineById(productLineId);
        User recorder = tokenService.getUserByRequest(req);
        if (tool == null) {
            return new JsonResult(ERROR_NULL_TOOL.getStatus(), ERROR_NULL_TOOL.getDesc());
        } else if (staff == null) {
            return new JsonResult(ERROR_NULL_STAFF.getStatus(), ERROR_NULL_STAFF.getDesc());
        } else if (location == null) {
            return new JsonResult(ERROR_NULL_LOCATION.getStatus(), ERROR_NULL_LOCATION.getDesc());
        } else if (productLine == null) {
            return new JsonResult(ERROR_NULL_PRODUCT_LINE.getStatus(), ERROR_NULL_PRODUCT_LINE.getDesc());
        } else if (recorder == null) {
            return new JsonResult(ERROR_NULL_RECORDER.getStatus(), ERROR_NULL_RECORDER.getDesc());
        } else if (recorder.getWorkcell().getId() != tool.getTDef().getWorkcell().getId()) {
            return new JsonResult(ERROR_OTHER_WORKCELL.getStatus(), ERROR_OTHER_WORKCELL.getDesc());
        }

        //判断要进行的操作与tool的状态是否一致
        Status useRecordStatus;
        if (status == 0) {
            //判断tool的状态，如果模具已在库则不可再入库
            if (tool.getStatus().getId() == TOOL_INDOOR.getStatus()) {
                return new JsonResult(ERROR_TOOL_STATUS_INDOOR.getStatus(), ERROR_TOOL_STATUS_INDOOR.getDesc());
            }
            useRecordStatus = useRecordStatusService.findById(USE_RECORD_IN.getStatus());

            // 入库记录更新 对应的出库记录 mask 为1
            UseRecord out = useRecordService.findUseRecordByToolId(tool.getId());
            out.setMask(1);
            useRecordService.updateUseRecordById(out);
        } else {
            //判断tool的状态，如果模具不在库则不可出库
            if (tool.getStatus().getId() != TOOL_INDOOR.getStatus()) {
                return new JsonResult(ERROR_TOOL_STATUS_OUTDOOR.getStatus(), ERROR_TOOL_STATUS_OUTDOOR.getDesc());
            }
            useRecordStatus = useRecordStatusService.findById(USE_RECORD_OUT.getStatus());
        }

        //添加进出库记录
        UseRecord useRecord = new UseRecord(productLine, staff, recorder, tool, time, location, useRecordStatus, 0);
        useRecordService.createUseRecord(useRecord);

        //添加生命周期库
        Status lifeCycleStatus = lifeCycleStatusService.findById(LIFE_USE_RECORD.getStatus());
        LifeCycle lifeCycle = new LifeCycle(tool, lifeCycleStatus, recorder.getId(), time, descriptionService.getDescription(useRecord));
        lifeCycleService.createLifeCycle(lifeCycle);

        //更新模具状态
        //根据status给tool更新状态，status为0时进库，为1时出库
        if (status == 0) {
            tool.setLocation(location);
            Status toolStatus = toolStatusService.findById(TOOL_INDOOR.getStatus());
            tool.setStatus(toolStatus);
        } else {
            //tool的使用记录只在出库时记录一下，进库时不再添加，以免重复
            tool.setUsedCount(tool.getUsedCount() + 1);
            Status toolStatus = toolStatusService.findById(TOOL_OUTDOOR.getStatus());
            tool.setStatus(toolStatus);
        }
        toolService.updateToolById(tool);
        return new JsonResult(SUCCESS.getStatus(), SUCCESS.getDesc(), new Data(useRecord));
    }

    /**
     * 分页查看进出库记录
     *
     * @param page     页数，默认为 1
     * @param pageSize 每页个数，默认为 5
     * @param status   需要查询的useRecord的状态，默认为-1即全部
     * @param request  获取workcellId，用于判断是否是同一部门
     * @return 成功返回查询的数据，失败返回错误信息
     */
    @GetMapping
    public JsonResult viewUseRecords(@RequestParam(value = "page", defaultValue = "1") int page,
                                     @RequestParam(value = "pageSize", defaultValue = "5") int pageSize,
                                     @RequestParam(value = "status", defaultValue = "-1") int status,
                                     HttpServletRequest request) {
        //取出token里存储的workcellId以判断是否是同一workcell
        int workcellId = tokenService.getWorkcellId(request);
        if (workcellId == 0) {
            return new JsonResult(ERROR_TOKEN.getStatus(), ERROR_TOKEN.getDesc());
        }
        PageInfo<UseRecord> info = useRecordService.findAllUseRecords(page, pageSize, status, workcellId);
        if (info != null && info.getSize() == 0) {
            return new JsonResult(ERROR_NULL_INFO.getStatus(), ERROR_NULL_INFO.getDesc());
        }
        return new JsonResult(SUCCESS.getStatus(), SUCCESS.getDesc(), new Data("useRecords", info));
    }

    /**
     * 分页查看 出库记录
     *
     * @param page     页数，默认为 1
     * @param pageSize 每页个数，默认为 5
     * @param request  获取workcellId，用于判断是否是同一部门
     * @return 成功返回查询的数据，失败返回错误信息
     */
    @GetMapping("/out")
    public JsonResult viewUseRecords(@RequestParam(value = "page", defaultValue = "1") int page,
                                     @RequestParam(value = "pageSize", defaultValue = "5") int pageSize,
                                     HttpServletRequest request) {
        //取出token里存储的workcellId以判断是否是同一workcell
        int workcellId = tokenService.getWorkcellId(request);
        if (workcellId == 0) {
            return new JsonResult(ERROR_TOKEN.getStatus(), ERROR_TOKEN.getDesc());
        }
        PageInfo<UseRecord> info = useRecordService.findAllOutUseRecords(page, pageSize, workcellId);
        return new JsonResult(SUCCESS.getStatus(), SUCCESS.getDesc(), new Data("useRecords", info));
    }

     /**
     * 查看某一确定的id的进出库记录
     *
     * @param id 记录id
     * @param request  获取workcellId，用于判断是否是同一部门
     * @return 如果是同一workcell部门并且成功查找则返回记录信息，反之则输出相关错误信息
     */
    @GetMapping("{id}")
    public JsonResult getUseRecord(@PathVariable(value = "id") int id, HttpServletRequest request) {
         //取出token里存储的workcellId以判断是否是同一workcell
        int workcellId = tokenService.getWorkcellId(request);
        if (workcellId == 0) {
            return new JsonResult(ERROR_TOKEN.getStatus(), ERROR_TOKEN.getDesc());
        }
        UseRecord useRecord = useRecordService.findUseRecordById(id);
        //如果没有找到该记录或者该记录与用户并不是同一 workcell
        if (useRecord == null) {
            return new JsonResult(ERROR_NULL_USERECORD.getStatus(), ERROR_NULL_USERECORD.getDesc());
        } else if (useRecord.getRecorder().getWorkcell().getId() != workcellId) {
            return new JsonResult(ERROR_OTHER_WORKCELL.getStatus(), ERROR_OTHER_WORKCELL.getDesc());
        }
        return new JsonResult(SUCCESS.getStatus(), SUCCESS.getDesc(), new Data(useRecord));
    }
}